package cn.android666.net.util.download.apkdownload

import androidx.appcompat.app.AppCompatActivity
import cn.android666.net.util.download.FileDownloader
import timber.log.Timber
import java.io.File

/**
 * Apk下载Presenter，用于控制下载、重新下载、暂停下载、恢复下载等功能。内部已经封装了View，所以，只需要调用startNewDownload函数即可开始下载
 * @param activity 用于显示对话框
 * @param isForeDownload 指示是否是强制下载，强制下载则不允许下载的过程中进行取消操作
 * @param install 如需要自己处理安装逻辑，则提供安装Apk的函数, String参数为apk文件的路径
 */
class ApkDownloadPresenter(
    private val activity: AppCompatActivity,
    isForeDownload: Boolean,
    install: ((String) -> Unit)? = null): ApkDownloadContract.Presenter {

    private var downloadView: ApkDownloadView = ApkDownloadView(activity, this, isForeDownload, install)
    private var fileDownloader: FileDownloader? = null

    /**
     * 如果需要自定义下载显示逻辑，则提供自定义的downloadView
     * @param downloadView
     */
    fun changeDownloadView(downloadView: ApkDownloadView) {
        this.downloadView = downloadView
    }

    override fun startNewDownload(appName: String, appDownloadUrl: String, appPackageName: String?, appVersionCode: String?, apkSaveDir: File) {
        Timber.d("开始下载apk：$appDownloadUrl")
        fileDownloader = FileDownloader(
            downloadUrl = appDownloadUrl,
            callback = downloadView,
            fileName = appName,
            fileSaveDir = apkSaveDir,
            saveFileName = "${appPackageName}_${appVersionCode}.apk"
        ).also { it.startDownload() }
    }

    override fun reDownload() = fileDownloader?.reDownload() ?: Unit
    override fun pauseDownload() = fileDownloader?.stopDownload() ?: Unit
    override fun resumeDownload() = fileDownloader?.startDownload() ?: Unit
    override fun isDownloading() = fileDownloader?.isDownloading ?: false
}